package com.tyut.musicdreamer.service.gateway.filter;

import cn.dev33.satoken.SaManager;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

/**
 * 认证头同步过滤器
 * 确保Authorization和satoken头保持一致
 */
@Component
@Slf4j
public class AuthHeaderSyncFilter implements GlobalFilter, Ordered {

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        ServerHttpRequest request = exchange.getRequest();
        
        // 获取token名称
        String tokenName = SaManager.getConfig().getTokenName();
        
        // 从请求头中获取Authorization
        String authHeader = request.getHeaders().getFirst("Authorization");
        // 从请求头中获取satoken
        String saTokenHeader = request.getHeaders().getFirst(tokenName);
        
        // 记录原始请求头
        log.debug("原始请求头: Authorization={}, {}={}, 请求路径={}, 请求方法={}", 
                authHeader, tokenName, saTokenHeader, 
                request.getPath(), request.getMethod());
        
        // 如果只有Authorization头，但没有satoken头
        if (authHeader != null && (saTokenHeader == null || saTokenHeader.isEmpty())) {
            // 添加satoken头
            ServerHttpRequest newRequest = request.mutate()
                    .header(tokenName, authHeader)
                    .build();
            
            log.debug("添加{}头: {}", tokenName, authHeader);
            return chain.filter(exchange.mutate().request(newRequest).build());
        }
        // 如果只有satoken头，但没有Authorization头
        else if (saTokenHeader != null && (authHeader == null || authHeader.isEmpty())) {
            // 添加Authorization头
            ServerHttpRequest newRequest = request.mutate()
                    .header("Authorization", saTokenHeader)
                    .build();
            
            log.debug("添加Authorization头: {}", saTokenHeader);
            return chain.filter(exchange.mutate().request(newRequest).build());
        }
        // 如果两者都存在，但不一致，则以satoken为准
        else if (authHeader != null && saTokenHeader != null && !authHeader.equals(saTokenHeader)) {
            // 构建新请求，以satoken为准
            ServerHttpRequest newRequest = request.mutate()
                    .header("Authorization", saTokenHeader)
                    .build();
            
            log.debug("同步认证头: Authorization={}", saTokenHeader);
            return chain.filter(exchange.mutate().request(newRequest).build());
        }
        
        return chain.filter(exchange);
    }

    @Override
    public int getOrder() {
        // 在TokenParamFilter之后执行
        return -120;
    }
} 